package com.chaoyong.higo.view;

import com.chaoyong.higo.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.text.Html;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 倒计时
 * 
 * @author zk
 *
 */
public class TimeTextView extends TextView implements Runnable {

	Paint mPaint;
	private long[] times;
	private long mhour, mmin, msecond;// 时分秒
	private boolean run = false;// 是否启动

	public TimeTextView(Context context) {
		super(context);
	}

	public TimeTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}

	public TimeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		mPaint = new Paint();
		TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeTextView);

		// 这个方法一定要调用
		array.recycle();
	}

	public long[] getTimes() {
		return times;
	}

	public void setTimes(long[] times) {
		this.times = times;
		mhour = times[0];
		mmin = times[1];
		msecond = times[2];
	}

	/**
	 * 倒计时计算
	 */
	private void computeTimes() {
		msecond--;
		if (msecond < 0) {
			mmin--;
			msecond = 59;
			if (mmin < 0) {
				mmin = 59;
				mhour--;
				if (mhour < 0) {
					// 倒计时结束
					this.setText("正在计算...");
				}
			}

		}
	}

	public boolean isRun() {
		return run;
	}

	public void setRun(boolean run) {
		this.run = run;
	}

	@Override
	public void run() {
		run = true;

		computeTimes();

		String strTimes = mhour + "</font>" + "小时" + "<font color=\"#FF0033\">" + 
							mmin + "</font>" + "分钟"+ "<font color=\"#FF0033\">" + 
								msecond + "</font>" + "秒";
		this.setText(Html.fromHtml(strTimes));
		postDelayed(this, 1000);
	}

}
